package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.Page;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Result;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper ;

    @Autowired
    private DishMapper dishMapper ;

    @Autowired
    private SetmealMapper setMealMapper ;

    //获取类型集合
    @Override
    public Result page(Integer page, Integer pageSize) {
        PageHelper.startPage(page , pageSize);
        List<Category> page1 = categoryMapper.page();
        PageInfo<Category> categoryPageInfo = new PageInfo<>(page1);
        Page<Category> categoryPage = new Page<>();
        categoryPage.setTotal(categoryPageInfo.getTotal());
        categoryPage.setRecords(categoryPageInfo.getList());
        return Result.success(categoryPage);
    }

    //添加分类
    @Override
    public void addCategory(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.addCategory(category);
    }

    //编辑分类
    @Override
    public void editCategory(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.editCategory(category);
    }

    //删除分类
    @Override
    public void deleteCategory(Long id) {

        List<Dish> dishByCategoryId = dishMapper.findDishByCategoryId(id);
        if(CollUtil.isNotEmpty(dishByCategoryId)){
            //判断集合是不是为空
            throw new BusinessException("该分类下菜品，不可以删除");
            //运行异常不用写抛出
        }
        List<Setmeal> setmealByCategoryId = setMealMapper.findSetmealByCategoryId(id);
        if(CollUtil.isNotEmpty(setmealByCategoryId)){
            throw new BusinessException("该分类下套餐，不可以删除");
        }
        categoryMapper.deleteCategory(id);
    }

    //获取类型集合
    @Override
    public Result findAllByType(Integer type) {
        List<Category> list = categoryMapper.findAllByType(type);
        return Result.success(list);
    }

}
